<template>
  <div>
    <a-upload
      :name="name"
      :action="UPLOAD_URL"
      :headers="headers"
      :data="params"
      list-type="picture-card"
      class="file-uploader"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      @change="handleChange"
      accept="image/*"
    >
      <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">上传照片</div>
      </div>
      <div class="uploadIcon" @click.stop="handleRemove">
        <img
          class="close"
          v-if="imageUrl"
          src="../../assets/icon-del.png"
          alt=""
          srcset=""
        />
      </div>
    </a-upload>
  </div>
</template>

<script>
import { UPLOAD_URL } from '@/const/const'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  props: {
    name: {
      type: String,
      default: 'file'
    },
    action: {
      type: String,
      default: process.env.VUE_APP_API_BASE_URL + UPLOAD_URL
    },
    value: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default: () => {}
    },
    uploadMode: {
      type: String,
      default: 'automat' // automat：自动，manual：手动
    }
  },
  data () {
    const imageArr = this.value
      ? [
          {
            uid: '-1',
            status: 'done',
            name: this.value,
            url: this.value,
            response: {
              url: this.value
            }
          }
        ]
      : []
    return {
      loading: false,
      imageUrl: this.value,
      UPLOAD_URL: this.action,
      headers: {
        Token: storage.get(ACCESS_TOKEN)
      },
      fileList: imageArr
    }
  },
  watch: {
    value (newValue, oldValue) {
      if (newValue) {
        this.imageUrl = newValue
      }
      if (!newValue) this.imageUrl = ''
    },
    action (newValue, oldValue) {
      // eslint-disable-next-line eqeqeq
      if (oldValue && newValue != oldValue) {
        this.UPLOAD_URL = process.env.VUE_APP_API_BASE_URL + newValue
      }
    }
  },
  methods: {
    // handleChange ({ file }) {
    //   if (file.status === 'done' && file.response && file.response.code === '000000') {
    //     this.imageUrl = file.response.data
    //     this.$emit('input', file.response.data)
    //   } else if (file.response && file.response) {
    //     this.$notification.error({
    //       message: '错误提示',
    //       description: file.response && file.response.msg || '上传失败'
    //     })
    //             }
    // }

  handleChange (info) {
      console.log(info)
      // if (this.uploadMode === 'automat') {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        if (info.file.status === 'done') {
          // console.log(info.file.response.data)
          this.imageUrl = info.file.response.data
          this.$emit('input', this.imageUrl)
          // this.$emit('update:relativePath', info.file.response.data.relativePath)
          this.$emit('change', info.file.response.data)
          // Get this url from response in real world.
          // getBase64(info.file.originFileObj, imageUrl => {
          //   this.imageUrl = imageUrl
          this.loading = false
          // })
        }
      // } else {
      //   getBase64(info.file).then(imageUrl => {
      //     this.imageUrl = imageUrl
      //     this.loading = false
      //     this.$emit('input', this.imageUrl)
      //     this.$emit('change', this.imageUrl)
      //   })
      // }
      // this.$emit('image', info)
    },
    handleRemove () {
      this.imageUrl = ''
      this.$emit('input', '')
      this.$emit('change', '')
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type.includes('image') // file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('请选择图片类型的文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M // && this.uploadMode == 'automat'
    }
  },
  components: {}
}
</script>

<style lang="less">
@import url('../../style/ant-design-variables.less');

.file-uploader .ant-upload.ant-upload-select-picture-card,
.file-uploader > .ant-upload img {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  position: relative;
}
.file-uploader .ant-upload.ant-upload-select-picture-card > .ant-upload {
  padding: 0;
}
.file-uploader > .ant-upload {
  > .ant-upload {
    padding: 0;
  }
}
.file-uploader .uploadIcon {
  position: absolute;
  right: -9px;
  top: -13px;
  .del,
  .close {
    font-size: 18px;
    color: @error-color;
  }
  .close {
    width: 20px;
    height: 20px;
    background-color: white;
  }
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.uploadMsg {
  color: @primary-color;
  width: 120px;
  text-align: center;
  .icon {
    margin-right: 7px;
    font-size: 15px;
  }
}
</style>
